<?php
/**
 * @author: Shauan Andrade < shauan@unimedteresina.com >
 * @copyright 2014 - 2014 PhpStorm
 * Date and time 14/10/14 - 17:17
 */

namespace helpers;

use core\App;
use ReCaptcha;
App::uses('ReCaptcha','vendor/ReCaptcha');

class ReCaptchaHelper{

    const PUBLICKEY = "6LeKvfQSAAAAAEYHC87OrNBKuV8n3NKDJ4_NuBxP";
    const PRIVATEKEY = "6LeKvfQSAAAAAKIE9KUsEP0WR8vOQ4bRitnZGZ74";
    private $recaptcha;

    public function __construct(){
        $this->recaptcha = new \ReCaptcha();
    }

    public function getHtml(){
        $html = $this->recaptcha->recaptcha_get_html(self::PUBLICKEY,'error');
        return $html;
    }

    public function _validCaptcha($param){
        if (isset($param["recaptcha_response_field"])) {
            if ($param["recaptcha_response_field"]) {
                $resp = $this->recaptcha->recaptcha_check_answer(self::PRIVATEKEY,
                    $_SERVER["REMOTE_ADDR"],
                    $param["recaptcha_challenge_field"],
                    $param["recaptcha_response_field"]);

                if ($resp->is_valid) {
                    $captchaValido = true;
                } else {
                    $captchaValido = false;
                }
            }else{
                $captchaValido = false;
            }
        }else{
            $captchaValido = false;
        }
        return $captchaValido;
    }

    public function validCaptcha($param){
        if (isset($param["g-recaptcha-response"]) and !empty($param["g-recaptcha-response"])) {
            $recaptcha = $param['g-recaptcha-response'];
            $url = "https://www.google.com/recaptcha/api/siteverify";
            $secret = "6Le0w_4SAAAAAO8bhaPwOLpdkX8UOuAj2fAV1LcZ";
            $ip = $_SERVER['REMOTE_ADDR'];
            $url .= "?secret=$secret&response=$recaptcha";
            $res = $this->apiRequest($url);
            $res= json_decode($res, true);
            $captchaValido = ($res['success']) ? true : false;
        }else{
            $captchaValido = false;
        }
        return $captchaValido;
    }

    private function apiRequest($url){
        return file_get_contents($url);
        /*$curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16");
        $curlData = curl_exec($curl);
        curl_close($curl);
        return $curlData;*/
    }

} 